<!--
* @author 谭玉泽
培训班资源列表
-->
<template>
  <div class="resources-container">
    <el-collapse-transition>
      <div v-show="searchshow" class="resources-search merge">
        <span class="svg-container">
          <svg-icon icon-class="search" />
        </span>
        <el-input
          v-model.trim="listQuery.name"
          placeholder="请输入名称搜索"
          class="search-input"
          @keyup.enter.native="handleFilter"
        />
        <div class="resources-search-btn">
          <el-button class="filter-item" type="primary" @click="handleFilter"
            >搜索</el-button
          >
          <el-button class="filter-item" type="primary" @click="resettingBtn"
            >重置</el-button
          >
        </div>
      </div>
    </el-collapse-transition>
    <!--    主按钮-->
    <div class="course-btn">
      <div class="btn-title">
        <span>班级资源管理 &nbsp;({{ className }})</span>
      </div>
      <div class="btn-btns">
        <!--        <el-button
          style="margin-left: 10px;"
          @click="handleCreate"
        >新建
        </el-button>-->
        <el-button
          v-if="
            (activeTab === 'ZYLX_ZB' || activeTab === 'ZYLX_XW') &&
            isAllowAddOwn
          "
          style="margin-left: 10px"
          @click="handleCreated()"
          >新建资源
        </el-button>
        <el-button
          v-if="isAllowAddOwn"
          style="margin-left: 10px"
          @click="handleSelect()"
          >选择资源
        </el-button>
        <el-button
          v-if="isAllowAddOwn"
          style="margin-left: 10px"
          @click="handleDeletes"
          >批量删除
        </el-button>
        <el-button style="margin-left: 10px" @click="handleBack"
          >返回
        </el-button>
      </div>
    </div>
    <!--  tabs-->
    <div class="classify-tab">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane
          v-for="(item, index) in dict['ZYLX']"
          :key="index"
          :label="item.dictName"
          :name="item.dictValue"
        />
      </el-tabs>
    </div>
    <!--    列表-->
    <div class="course-list">
      <!--      :key="myTime"-->
      <v-table
        v-if="tag"
        :list="resourcesList"
        :tag="tag"
        :list-loading="listLoading"
        :filter-column="filtercolumn"
        :source-arr="sourceArr"
        :selection="true"
        :toggle-row-selection="toggleRowSelection"
        @handleSelectionChange="handleSelectionChange"
      >
        <el-table-column
          fixed="right"
          label="可获得学时"
          width="160"
          align="center"
          prop="getReward"
        />
        <el-table-column
          fixed="right"
          label="是否必修"
          width="160"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.definition === "1" ? "必修" : "选修" }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="160" align="center">
          <template slot-scope="scope">
            <el-button
              v-if="
                ((activeTab === 'ZYLX_ZB' && scope.row.resourcesSource === 2) ||
                  (activeTab === 'ZYLX_XW' &&
                    scope.row.resourcesSource === 2)) &&
                isAllowAddOwn &&
                !scope.row.isSaas
              "
              type="text"
              size="small"
              @click="handleUpdateData(scope.row)"
            >
              编辑
            </el-button>
            <el-button type="text" size="small" @click="handleUpdate(scope.row)"
              >设置</el-button
            >
            <el-button type="text" size="small" @click="handleSort(scope.row)"
              >修改排序</el-button
            >
            <el-button
              v-if="isAllowAddOwn && !scope.row.isSaas"
              type="text"
              size="small"
              @click="handleDel(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </v-table>
    </div>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getPage"
    />

    <!--    选择资源-->
    <el-dialog
      :close-on-click-modal="false"
      custom-class="live-dialog"
      destroy-on-close
      :visible.sync="chooseResources"
      title="选择数据"
      width="1200px"
      center
    >
      <choose-course
        v-if="chooseResources"
        ref="chooseCourse"
        :key="activeTab"
        :is-get="chooseResources"
        :is-child="false"
        :tag="tag"
        :url-type="activeTab"
        :area-id="areaId"
        :selection="true"
        :classify-type="classifyType"
        @select="selectMany"
        @selectMany="selectMany"
        @updateDefinition="updateDefinition"
        @updateGetReward="updateGetReward"
        @updateDragMark="updateDragMark"
      />
      <div slot="footer" class="dialog-footer">
        <el-button
          type="default"
          style="padding: 10px 30px"
          @click="handleClose"
          >取 消</el-button
        >
        <el-button
          type="primary"
          style="padding: 10px 30px"
          @click="handleSubmit"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 修改资源类型 -->
    <el-dialog
      v-el-drag-dialog
      width="500px"
      title="修改资源设置"
      :visible.sync="dialogStatusVisible"
      center
      :close-on-click-modal="false"
    >
      <el-form ref="form">
        <el-row>
          <el-col :span="24">
            <el-form-item label="允许视频拖拽">
              <el-switch v-model="modDragMark" @change="changeDradMark(modDragMark)"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="是否必修">
              <el-radio-group v-model="courseData.definition">
                <el-radio label="1">必修</el-radio>
                <el-radio label="2">选修</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="请输入可获得学时">
              <el-form-item>
                <el-input-number
                  v-model="courseData.getReward"
                  :controls="false"
                  :min="0"
                  placeholder="请输入可获得学时"
                />
              </el-form-item>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          style="padding: 8px 30px"
          @click="dialogStatusVisible = false"
          >取消</el-button
        >
        <el-button
          style="padding: 8px 30px"
          type="primary"
          @click="handleUpdateResourse()"
          >确定</el-button
        >
      </div>
    </el-dialog>

    <!-- 修改排序 -->
    <el-dialog
      title="修改排序"
      width="30%"
      :visible.sync="sortDialog"
      @close="cancelDialog"
      v-el-drag-dialog
    >
      <el-input
        v-model="form.sort"
        placeholder="请输入排序值"
        type="number"
      ></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">取 消</el-button>
        <el-button type="primary" @click="handelUpdateSort">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import { queryPage, insert, del, getDictByCode, updateResource, updateSort  } from '../api/index'
import { mapGetters } from 'vuex'
import elDragDialog from '@/directive/el-drag-dialog'
import vTable from '@/components/Table'
import ChooseCourse from '../components/chooseCourse' // 选择资源

export default {
  name: 'ResourcesIndex',
  components: { Pagination, vTable, ChooseCourse },
  directives: { elDragDialog },
  data() {
    return {
      areaId: '', // 培训班id
      chooseResources: false, // 选择资源的弹框
      isFull: false, // 是否全屏
      listLoading: false,
      searchshow: true,
      total: 0,
      listQuery: {
        page: 1,
        limit: 10,
        name: ''
      },
      resourcesList: [], // 数据列表
      activeTab: '', // 资源类型
      sourceArr: ['headImgURL', 'subjectImgUrl', 'courseImgUrl', 'img', 'imgIdUrl', 'coverImgIdUrl', 'imgURL', 'coverImgIdUrl'],
      link: '/study/detail?i=',
      dict: {
        ZYLX: [] // 资源类型
      },
      view: '/API-DOCUMENT/document/file/download?id=',
      tagList: {
        // ZYLX_SP: 'contentVideoLibrarRelease', // 视频
        ZYLX_YP: 'courseManagement', // 音频
        ZYLX_ZL: 'documentLibraryLibrarRelease', // 资料
        ZYLX_XW: 'newsZoneClass', // 新闻
        ZYLX_ZB: 'liveIndex', // 直播
        // ZYLX_HD: 'documentLibraryLibrarRelease', // 活动
        ZYLX_KS: 'examManagement', // 考试
        ZYLX_CG: 'resourceAddRecruit', // 闯关
        ZYLX_ZQ: 'documentLibraryLibrarRelease', // 专区
        ZYLX_TP: 'imgLibrary', // 图片
        ZYLX_ZXDT: 'newSpecial', // 专项答题
        ZYLX_DCWJ: 'surveyMain', // 调查问卷
        ZYLX_TPHD: 'vote', // 投票活动
        ZYLX_KC: 'courseManagement', // 课程
        ZYLX_RW: 'train-characterlibrary' // 人物
      },
      classifyTypeList: {
        // ZYLX_SP: 'contentVideoLibrarRelease', // 视频
        ZYLX_YP: 'JNZQFL08', // 音频
        ZYLX_ZL: 'JNZQFL07', // 资料
        ZYLX_XW: 'XWFL_XWGL', // 新闻
        ZYLX_ZB: '', // 直播
        // ZYLX_HD: 'documentLibraryLibrarRelease', // 活动
        ZYLX_KS: 'JNZQFL09', // 考试
        ZYLX_CG: 'JNZQFL04', // 闯关
        ZYLX_ZQ: 'documentLibraryLibrarRelease', // 专区
        ZYLX_TP: 'imgLibrary', // 图片
        ZYLX_ZXDT: '', // 专项答题
        ZYLX_DCWJ: '', // 调查问卷
        ZYLX_TPHD: '', // 投票活动
        ZYLX_KC: 'JNZQFL01', // 课程
        ZYLX_RW: 'RWFL' // 人物
      },
      ids: '', // 选择资源ids
      definition: '', // 选择资源ids
      getReward: '', // 选择资源ids
      tag: '',
      classifyType: '',
      multipleSelection: [], // 多选
      myTime: new Date().getTime(),
      dialogStatusVisible: false,
      courseData: {},
      isAllowAddOwn: false, // 是否能添加自有资源
      form: {
        id: '',
        sort: ''
      },
      sortDialog: false,
      addDragMark: true,
      modDragMark: true
    }
  },
  computed: {
    /* tag() {
      return this.tagList[this.activeTab]
    }*/
  },
  watch: {
    activeTab() {
      this.myTime = new Date().getTime()
    }
  },
  async created() {
    if (!this.$route.query.id) {
      this.$message({
        showClose: true,
        message: '参数异常！',
        type: 'warning',
        onClose: () => {
          this.$router.back()
        }
      })
      return
    } else {
      this.areaId = this.$route.query.id
      this.className = this.$route.query.name
      this.isAllowAddOwn = !(this.$route.query.isAllowAddOwn === 0)
      for (const key in this.dict) {
        await this.getDict(key)
      }
      this.getPage()
    }
  },
  methods: {
    toggleRowSelection(row, selected) { },
    filtercolumn(scope, item) {
      if (item === 'img') {
        return `${this.view + scope.row['coverImgId']}`
      } else if (item === 'isShowNumber') {
        return scope.row[item] === '0' ? '否' : '是'
      } else if(item === 'belongValue') {
        return scope.row.dataSources || '未知'
      }
      return scope.row[item]
    },
    /**
     * 字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code)
          .then((response) => {
            this.dict[code] = response.data.data[0].list
            if (code === 'ZYLX') {
              this.activeTab = this.$route.query.c || this.dict.ZYLX[0].dictValue
              this.tag = this.tagList[this.activeTab] || 'courseManagement'
              this.classifyType = this.classifyTypeList[this.activeTab] || 'JNZQFL08'
            }
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    /**
     *多选
     */
    handleSelectionChange(arr) {
      this.multipleSelection = arr
    },

    /**
     * 选择资源
     */
    selectMany({ arr, definition, getReward }) {
      const idArr = []
      if (arr.length > 0) {
        arr.forEach((item) => {
          idArr.push(item.id)
        })
        this.ids = idArr.join(',')
        this.definition = definition
        this.getReward = getReward
      }
    },
    updateDefinition(val) {
      this.definition = val
    },
    updateGetReward(val) {
      this.getReward = val
    },
    updateDragMark(val) {
      this.addDragMark = val
      console.log(this.addDragMark);
    },
    /**
     * 提交选择的资源
     */
    handleSubmit() {
      if (this.ids === '') {
        this.$message({
          message: '请选择需要添加的资源！',
          type: 'warning'
        })
        return
      }
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      const params = {
        areaId: this.areaId,
        type: this.activeTab,
        source: '1',
        dataId1: this.ids,
        getReward: this.getReward,
        definition: this.definition,
        dragMark: this.addDragMark === true ? '1' : '0'
      }
      return new Promise((resolve, reject) => {
        insert(params)
          .then(() => {
            loading.close()
            this.$message({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
            this.chooseResources = false
            this.getPage()
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    },
    /**
     * 批量删除
     */
    handleDeletes() {
      const arr = []
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach((item) => {
          arr.push(item.resourcesId)
        })
        const ids = arr.join(',')
        this.handleDelete(ids)
      } else {
        this.$message({
          message: '请选择需要删除的数据！',
          type: 'warning'
        })
      }
    },
    handleBack() {
      // this.$router.back()
      this.$router.push({
        path: this.$filterPath('index')
      })
    },
    // 编辑
    handleUpdate(row) {
      this.courseData = { ...row }
      this.modDragMark = this.courseData.dragMark === '1' ? true : false
      this.dialogStatusVisible = true
    },
    // 确定编辑
    handleUpdateResourse() {
      return new Promise((resolve, reject) => {
        updateResource({
          id: this.courseData.resourcesId,
          definition: this.courseData.definition,
          getReward: this.courseData.getReward,
          dragMark: this.courseData.dragMark
        })
          .then(() => {
            this.$message({
              title: '成功',
              message: '设置成功',
              type: 'success',
              duration: 2000
            })
            this.dialogStatusVisible = false
            this.getPage()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    handleDel(row) {
      this.handleDelete(row.resourcesId)
    },
    /**
     * 删除
     */
    handleDelete(ids) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          return new Promise((resolve, reject) => {
            del({
              ids: ids
            })
              .then(() => {
                loading.close()
                this.$message({
                  title: '成功',
                  message: '删除成功',
                  type: 'success',
                  duration: 2000
                })
                this.getPage()
              })
              .catch((error) => {
                loading.close()
                reject(error)
              })
          })
        })
        .catch(() => { })
    },
    /**
     * 选择资源
     */
    handleSelect(type) {
      this.chooseResources = true
      this.$nextTick(() => {
        if (this.classifyType === 'RWFL') {
          this.$refs.chooseCourse.getClassifyTreeRWFL()
        } else {
          this.$refs.chooseCourse.getClassifyOption()
        }
        this.$refs.chooseCourse.getList()
        this.$refs.chooseCourse.getReward = '0'
        this.$refs.chooseCourse.definition = '1'
        this.$refs.chooseCourse.classifyId = ''
      })
    },
    // 新建资源
    handleCreated() {
      if (this.activeTab === 'ZYLX_XW') {
        this.$router.push({
          path: this.$filterPath('newManageResources'),
          query: { type: 'c', c: this.activeTab, id: this.$route.query.id, name: this.$route.query.name }
        })
      } else {
        this.$router.push({
          path: this.$filterPath('liveManageResources'),
          query: { type: 'c', c: this.activeTab, id: this.$route.query.id, name: this.$route.query.name }
        })
      }
    },
    // 编辑直播跟新闻
    handleUpdateData(row) {
      if (this.activeTab === 'ZYLX_XW') {
        this.$router.push({
          path: this.$filterPath('newManageResources'),
          query: { type: 'u', c: this.activeTab, id: this.$route.query.id, name: this.$route.query.name, i: row.id }
        })
      } else {
        this.$router.push({
          path: this.$filterPath('liveManageResources'),
          query: { type: 'u', c: this.activeTab, id: this.$route.query.id, name: this.$route.query.name, i: row.id }
        })
      }
    },

    /**
     * 取消选择
     */
    handleClose() {
      this.chooseResources = false
    },
    /**
     * 选项卡切换
     */
    handleTabClick(tab, event) {
      setTimeout(() => {
        this.tag = this.tagList[this.activeTab]
        this.classifyType = this.classifyTypeList[this.activeTab]
        this.listQuery.page = 1
        this.getPage()
      }, 500)
    },

    /**
     * 获取列表
     */
    getPage(obj) {
      this.listLoading = true
      var query = {
        areaId: this.areaId,
        type: this.activeTab,
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit
      }
      if (this.searchshow) {
        query['name'] = this.listQuery.name
      }
      delete query.selectType
      return new Promise((resolve, reject) => {
        queryPage(query)
          .then((response) => {
            this.listLoading = false
            this.resourcesList = response.data.data.rows
            this.total = response.data.data.total
          })
          .catch((error) => {
            this.listLoading = false
            reject(error)
          })
      })
    },

    /**
     *搜索
     */
    handleFilter() {
      this.listQuery.page = 1
      this.getPage()
    },

    /**
     *重置
     */
    resettingBtn() {
      this.listQuery.name = ''
      this.listQuery.title = ''
      this.listQuery.page = 1
      this.getPage()
    },

    // 修改排序
    handelUpdateSort() {
      if (this.form.sort === '') {
        this.$message({
          message: '请输入排序值',
          type: 'warning'
        })
        return
      }
      const obj = Object.assign({}, this.form)
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      updateSort(obj).then(res => {
        if (res.data.code === '200') {
          loading.close()
          this.sortDialog = false
          this.$message({
            message: '修改成功',
            type: 'success'
          })
          this.getPage()
        } else {
          loading.close()
          this.$message({
            message: '修改失败',
            type: 'error'
          })
        }
      }).catch(() => {
        loading.close()
      })
    },

    handleSort(row) {
      console.log(row, '482');
      this.form.id = row.resourcesId
      this.sortDialog = true
    },

    // 取消修改排序
    cancelDialog() {
      this.sortDialog = false
      for (let k in this.form) {
        this.form[k] = ''
      }
    },
    changeDradMark(val){
      this.courseData.dragMark = val === true ? '1' : '0'
      console.log(this.courseData.dragMark);
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
$dark_gray: #bfced6;
.resources-container {
  padding: 10px;

  .resources-search {
    background-color: #fff;
    padding: 0 20px;

    .svg-container {
      padding: 0 5px 0 10px;
      color: $dark_gray;
      vertical-align: middle;
      display: inline-block;

      &_login {
        font-size: 20px;
      }
    }

    .search-input {
      width: 60%;
      position: relative;

      &:after {
        content: "";
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }

      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;

        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }

    .resources-search-btn {
      display: inline-block;
      float: right;

      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }

      .resources-search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
      }
    }

    &.merge {
      height: 50px;
      line-height: 50px;
    }

    &.separate {
      .resources-search-inner {
        padding-top: 10px;

        .search-inner-item {
          .item-label {
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #a6a6a6;
            font-weight: 400;
          }

          .el-input {
            position: relative;

            .el-input__inner {
              border: none;
              padding: 0;
            }

            &:after {
              content: "";
              height: 1px;
              background-color: #e2e3e8;
              position: absolute;
              left: 0;
              right: 0;
              bottom: 0;
            }
          }
        }
      }

      .resources-search-btn {
        text-align: center;
        display: block;
        float: none;
        height: 56px;
        line-height: 56px;
      }
    }
  }

  .course-classify {
    display: flex;
    background-color: #fff;
    margin-top: 10px;
    margin-bottom: 10px;

    .course-classify-inner {
      flex: 1;

      .inner-item {
        position: relative;

        ul {
          padding: 5px 20px;
          margin: 0;
          box-shadow: 0 5px 10px rgba(254, 90, 97, 0.05);
          max-height: 50px;
          transition: all 1s ease;
          overflow: hidden;

          li {
            list-style-type: none;
            display: inline-block;
            padding: 6px 12px;
            font-size: 14px;
            font-family: PingFangSC-Medium;
            font-weight: 500;
            color: rgba(51, 51, 51, 1);
            margin: 5px;
            cursor: pointer;

            &:first-child {
              margin: 0;
              padding: 0;
              color: #a6a6a6;
            }

            &.active {
              color: $mainColor;
              background: #eaf7ff;
              border-radius: 17px;
            }
          }

          &.toggle {
            max-height: 300px;
          }
        }

        span {
          position: absolute;
          right: 10px;
          top: 12px;
          color: $mainColor;
          cursor: pointer;
          font-size: 20px;
        }
      }
    }

    .course-classify-btn {
      position: relative;
      width: 150px;

      .el-button {
        position: absolute;
        top: 50%;
        margin-top: -15px;
        left: 50%;
        margin-left: -49px;
      }
    }
  }

  .course-btn {
    display: flex;
    height: 46px;
    line-height: 46px;
    width: 100%;

    .btn-title {
      flex: 1;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
    }
  }

  .course-list {
    .el-image {
      width: 100%;
      height: auto;
      max-height: 140px;
    }
  }

  .pagination-container {
    background: none;
  }

  .classify-tab {
    width: 100%;
    margin: 10px 0;
    padding: 0 10px;
    background-color: #fff;
    border-radius: 4px;

    .el-tabs__nav-next {
      line-height: 40px;
    }

    .el-tabs__nav-wrap::after {
      display: none;
    }

    .el-tabs__header {
      margin: 0;
    }
  }

  .view-item {
    margin-bottom: 10px;

    .view-content {
      color: #333;
      font-weight: 500;
    }
  }

  .see-dialog {
    height: 460px;
    overflow-y: auto;
    .textarea-view {
      white-space: pre-line;
      border: 1px solid #e5e5e5;
      border-radius: 6px;
      padding: 10px;
      color: #333;
      background-color: #f9f9f9;
      font-weight: normal;
    }
  }

  .my-title {
    width: 100%;
    display: inline-block;
    font-size: 16px !important;
    font-family: PingFangSC-Medium !important;
    font-weight: 700 !important;
    color: #333333 !important;
    position: relative;
    .full {
      position: absolute;
      width: 100px;
      height: 58px;
      right: 50px;
      top: -18px;
      display: flex;
      align-items: center;
      text-align: right;
    }
  }
}
</style>
